# -*- coding: utf-8 -*-

import logging
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkecs.request.v20140526.UnassignPrivateIpAddressesRequest import UnassignPrivateIpAddressesRequest
from aliyunsdkecs.request.v20140526.AssignPrivateIpAddressesRequest import AssignPrivateIpAddressesRequest

# To enable the initializer feature (https://help.aliyun.com/document_detail/158208.html)
# please implement the initializer function as below：
# def initializer(context):
#    logger = logging.getLogger()  
#    logger.info('initializing')


def handler(environ, start_response):
    context = environ['fc.context']
    request_uri = environ['fc.request_uri']
    eni_ip = ''
    eni_id = ''
    credentials = AccessKeyCredential('LTAI5txxxxxxxxxMhSjAoz', '7eGb4yyxxxxxxxxxxFDlGuxOEE5G2E')
    client = AcsClient(region_id='cn-hangzhou', credential=credentials)

    for k, v in environ.items():
        #try:
            #print(k+' '+v)
        #except:
        #    continue
        if k.startswith('HTTP_ENI_ID'):
            eni_id = v
            #print("ENI_ID: " + v)
        if k.startswith('HTTP_ENI_IP'):
            eni_ip = v
            #print("ENI_IP: " + v)
        if k.startswith('PATH_INFO'):
            #print("Method:" + v)
            if v.startswith('/add'):
                request = AssignPrivateIpAddressesRequest()
            if v.startswith('/remove'):
                request = UnassignPrivateIpAddressesRequest()

    # do something here    
    request.set_accept_format('json')
    output = b''
    try:
        request.set_PrivateIpAddresss([eni_ip])
        request.set_NetworkInterfaceId(eni_id)

        response = client.do_action_with_exception(request)
        print(str(response, encoding='utf-8'))
        output = b'Done'
    except:
        output = b'Error'
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    return [output]